<#assign object = doc.object />
package ${object.package}.gwt.client;

import java.util.Iterator;
import java.util.Set;
<#if object.trashcan == "true">
import java.util.ArrayList;
import java.util.List;
</#if>
import java.util.HashMap;

import ${object.package}.gwt.constants.*;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
<#if object.attributes.date[0]?? || object.attributes.datetime[0]??>
import java.util.Date;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.user.datepicker.client.DatePicker;
</#if>
import com.google.gwt.libideas.validation.client.ValidatorController;
import redora.client.validation.*;

<#if object.attributes.html[0]??>
import redora.client.ui.text.RichTextToolbar;
import com.google.gwt.user.client.ui.Grid;
</#if>
import com.google.gwt.gen2.table.client.FixedWidthFlexTable;
import com.google.gwt.gen2.table.client.FixedWidthGrid;
import com.google.gwt.gen2.table.client.ScrollTable;
import com.google.gwt.gen2.table.client.SelectionGrid.SelectionPolicy;
import com.google.gwt.gen2.table.override.client.FlexTable.FlexCellFormatter;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.json.client.JSONNull;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
<#if object.attributes.enum[0]?? || object.attributes.object[0]??>
import com.google.gwt.user.client.ui.ListBox;
</#if>
import com.google.gwt.user.client.ui.LazyPanel;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.TextBox;
<#if object.attributes.html[0]??>
import com.google.gwt.user.client.ui.RichTextArea;
</#if>
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.FormPanel.SubmitEvent;

public class ${object.name}ViewPanel extends LazyPanel {

	public ScrollTable scrollTable = null;
	
	public FlexTable buttonTable = new FlexTable();

	Constants constants = GWT.create(Constants.class);
	
	Messages messages = GWT.create(Messages.class);
	
	private String baseUrl = "../${object.name?uncap_first}Operations.do?";
	
	FlowPanel root = new FlowPanel();
	
	<#if object.attributes.date[0]??>
	private final String DATE = "yyyy-MM-dd";
	</#if>
	
	<#if object.attributes.datetime[0]??>
	private final String DATETIME = "yyyy-MM-dd HH:mm:ss";
	</#if>
	
	<#if object.trashcan == "true">
	List<Long> idList = new ArrayList<Long>();
	</#if>
	
	HashMap<Long, JSONObject> ${object.name?uncap_first}Map = new HashMap<Long, JSONObject>();
	
	final FlexTable formTable = new FlexTable();
	final TextBox id = new TextBox();
	<#list object.formScope?children as att>
		<#if att?node_name != "object" && att?node_type == "element">
			<#if att?node_name == "long">
				<#if att.@parentClass[0]??>
	final ListBox ${att.@fieldName} = new ListBox();
				<#else>
	final TextBox ${att.@fieldName} = new TextBox();
				</#if>
			<#elseif att?node_name == "enum">
	final ListBox ${att.@fieldName} = new ListBox();
			<#elseif att?node_name == "boolean">
	final CheckBox ${att.@fieldName}CheckBox = new CheckBox();
	final TextBox ${att.@fieldName} = new TextBox();
			<#elseif att?node_name == "html">
	final TextBox ${att.@fieldName} = new TextBox();
	final RichTextArea ${att.@fieldName}RichText = new RichTextArea();
			<#else>
	final TextBox ${att.@fieldName} = new TextBox();
			</#if>
		</#if>
	</#list>
	final TextBox creationDate = new TextBox();
	final TextBox updateDate = new TextBox();
	final FormPanel form = new FormPanel();
	
	JSONObject page = new JSONObject();

	public ${object.name}ViewPanel() {
	}
	
	public Widget createWidget() {
		// Combine the components into a ScrollTable
		final ScrollTable scrollTable = createScrollTable();

		createDataList(true);

		VerticalPanel panel = new VerticalPanel();

		panel.setWidth("100%");
		
		buttonTable = initButtons();
		
		FlexTable pageTable = new FlexTable();

        HTML first = new HTML("<a href=#>first</a>");
        first.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                page.put("position", JSONParser.parse("0").isNumber());
                scrollTable.getDataTable().clearAll();
                createDataList(true);
            }

        });

        HTML last = new HTML("<a href=#>last</a>");
        last.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                int position = Integer.parseInt(page.get("pageCount").toString()) - 1;
                page.put("position", JSONParser.parse(String.valueOf(position)).isNumber());
                scrollTable.getDataTable().clearAll();
                createDataList(true);
            }

        });

        HTML next = new HTML("<a href=#>>></a>");
        next.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                int position = Integer.parseInt(page.get("position").toString()) + 1;
                page.put("position", JSONParser.parse(String.valueOf(position)).isNumber());
                scrollTable.getDataTable().clearAll();
                createDataList(true);
            }

        });

        HTML previous = new HTML("<a href=#><<</a>");
        previous.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                int position = Integer.parseInt(page.get("position").toString()) - 1;
                page.put("position", JSONParser.parse(String.valueOf(position)).isNumber());
                scrollTable.getDataTable().clearAll();
                createDataList(true);
            }

        });

        final TextBox positon = new TextBox();
        positon.setWidth("30");

        HTML gotoPos = new HTML("<a href=#>goto</a>");
        gotoPos.addClickHandler(new ClickHandler() {

            public void onClick(ClickEvent event) {
                int position = Integer.parseInt(positon.getValue()) - 1;
                page.put("position", JSONParser.parse(String.valueOf(position)).isNumber());
                scrollTable.getDataTable().clearAll();
                createDataList(true);
            }

        });

        pageTable.setWidget(0, 0, first);
        pageTable.setWidget(0, 1, next);
        pageTable.setWidget(0, 2, positon);
        pageTable.setWidget(0, 3, gotoPos);
        pageTable.setWidget(0, 4, previous);
        pageTable.setWidget(0, 5, last);
		
		//panel.add(pageTable);
		panel.add(buttonTable);

		// Add the components to the page
		root.add(scrollTable);
		root.add(panel);
		return root;
	}
	
	/**
	 * Create the scroll table.
	 * 
	 * @return a data table
	 */
	public ScrollTable createScrollTable() {
		FixedWidthFlexTable headerTable = createHeaderTable(true);
		FixedWidthFlexTable footerTable = createFooterTable();
		FixedWidthGrid dataTable = createDataTable(true);

		// Combine the components into a ScrollTable
		scrollTable = new ScrollTable(dataTable, headerTable);
		scrollTable.setFooterTable(footerTable);

		// Set some options in the scroll table
		// scrollTable.setSortingEnabled(true);
		scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
		scrollTable.setSize("100%", "500");

		// Setup some default widths
		//scrollTable.setColumnWidth(2, 50);
		//scrollTable.setColumnWidth(5, 50);

		// Return the data table
		return scrollTable;
	}
	
	/**
	 * Create the data table.
	 * 
	 * @return a data table
	 */
	public FixedWidthGrid createDataTable(boolean showSetField) {
		// Create a new table
		//FixedWidthGrid dataTable = new FixedWidthGrid();
		FixedWidthGrid dataTable = new FixedWidthGrid() {
			public void onBrowserEvent(Event event) {
				this
						.sinkEvents(Event.ONBLUR | Event.ONCLICK
								| Event.ONDBLCLICK);
				PopupPanel popupPanel;
				if (event.getTypeInt() == Event.ONDBLCLICK) {
					Element element = this.getEventTargetRow(event);
					this.selectRow(this.getRowIndex(element), true);
					popupPanel = createPopupPanel(false);
					popupPanel.setGlassEnabled(true);
					popupPanel.setAnimationEnabled(true);
					popupPanel.center();
					popupPanel.show();
				} else {
					super.onBrowserEvent(event);
				}
			}
		};
		// dataTable.setSelectionPolicy(SelectionGrid.SelectionPolicy.MULTI_ROW);

		dataTable.setSelectionPolicy(SelectionPolicy.CHECKBOX);
		
		<#assign position = 1 />
		<#list object.tableScope?children as att>
	  		<#if att?node_type == "element">
	  			<#assign position = position + 1 />
	  		</#if>
		</#list>
		if (!showSetField)
			dataTable.resizeColumns(${position});
		else
		<#list object.attributes.set as att>
			<#assign position = position + 1 />	
		</#list>
			dataTable.resizeColumns(${position});

		// Return the data table
		return dataTable;
	}
	
	/**
	 * Get the ${object.name} Data List.
	 * 
	 */
	private void createDataList(final boolean showSetField) {
		final FixedWidthGrid dataTable = scrollTable.getDataTable();
		//if (page.keySet().isEmpty()) {
        //    page.put("mode", JSONParser.parse("'page'"));
        //    page.put("scope", JSONParser.parse("'Table'").isString());
        //    page.put("pageSize", JSONParser.parse("10").isNumber());
        //    page.put("resultCount", JSONParser.parse("-1").isNumber());
        //    page.put("position", JSONParser.parse("-1").isNumber());
        //}
		//String _url = URL.encode(baseUrl + "_operationType=fetch&fetchScope=table&page=" + page.toString());
        String _url = URL.encode(baseUrl + "_operationType=fetch&fetchScope=table");
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("createDataList failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONObject responseJSON = JSONParser.parse(response.getText())
						.isObject().get("response").isObject();
				if (!hasErrors(responseJSON)) {
					JSONArray array = responseJSON.get("data").isArray();
					copyValue(dataTable, array, showSetField);
					//page = responseJSON.get("page").isObject();
				}
				
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}
	
	public FixedWidthFlexTable createFooterTable() {
		return new FixedWidthFlexTable();
	}
	
	public FixedWidthFlexTable createHeaderTable(boolean showSetField) {
		// Create a new table
		FixedWidthFlexTable headerTable = new FixedWidthFlexTable();
		FlexCellFormatter formatter = headerTable.getFlexCellFormatter();

		final CheckBox selectAll = new CheckBox();
		selectAll.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (selectAll.getValue()) {
					scrollTable.getDataTable().selectAllRows();
				} else {
					scrollTable.getDataTable().deselectAllRows();
				}
			}

		});
		headerTable.setWidget(0, 0, selectAll);
		formatter.setHorizontalAlignment(0, 0,
				HasHorizontalAlignment.ALIGN_CENTER);
		headerTable.setHTML(0, 1, "Id");
		formatter.setHorizontalAlignment(0, 1,
				HasHorizontalAlignment.ALIGN_CENTER);
				
		<#assign position = 1 />
		<#list object.tableScope?children as att>
			<#if att?node_type == "element">
			  	<#if att?node_name == "date" || att?node_name == "datetime">
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
			  	<#elseif att?node_name == "enum">
			  	<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@fieldName}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
			  	<#elseif att?node_name == "object">
			  	<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@fieldName}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
			  	<#elseif att?node_name == "html" || att?node_name == "string">
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
				<#elseif att?node_name == "boolean">
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);		   
				<#elseif att?node_name == "integer">
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);	    
				<#elseif att?node_name == "long">
					<#if att.@parentClass[0]??>
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@fieldName}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
					<#else>
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
					</#if>	    
				<#elseif att?node_name == "double">
				<#assign position = position + 1 />
		headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@name}_table());
		formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
				<#else>
		ERROR, undefined node ${att?node_name}
				</#if>
			</#if>
		</#list>
		if (showSetField) {
		<#list object.attributes.set as att>
			<#assign position = position + 1 />
			headerTable.setHTML(0, ${position}, constants.${object.name?uncap_first}_${att.@plural}_table());
			formatter.setHorizontalAlignment(1, ${position},HasHorizontalAlignment.ALIGN_CENTER);
		</#list>	
		}

		// Return the header table
		return headerTable;
	}
	
	public FlexTable initButtons() {
		final FlexTable table = new FlexTable();
		table.setWidth("500");

		HTML add = new HTML("<a href=javascript:void(0)>New</a>");
		add.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent arg0) {
				scrollTable.getDataTable().deselectAllRows();
				PopupPanel popupPanel = createPopupPanel(true);
				popupPanel.setGlassEnabled(true);
				popupPanel.setAnimationEnabled(true);
				popupPanel.center();
				popupPanel.show();
			}
		});
		
		HTML delete = new HTML("<a href=javascript:void(0)>Delete</a>");
		delete.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (scrollTable.getDataTable().getSelectedRows().size() < 1) {
					Window.alert("You must select a record first!");
					return;
				}
				Set<Integer> set = scrollTable.getDataTable().getSelectedRows();
				Iterator<Integer> it = set.iterator();
				String ids = "";
				while (it.hasNext()) {
					final int row = it.next();
					String id = scrollTable.getDataTable().getText(row, 0);
					if (ids.isEmpty())
                        ids = id;
                    else
                        ids = ids + "," + id ;
				}
				String _url = URL.encode(baseUrl + "_operationType=remove&id=" + ids);
				RequestBuilder builder = new RequestBuilder(
						RequestBuilder.GET, _url);
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("Remove failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						JSONObject responseJSON = JSONParser.parse(response.getText())
							.isObject().get("response").isObject();
						if (!hasErrors(responseJSON)) {
							scrollTable.getDataTable().clearAll();
							createDataList(true);
						}
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}
		});
		
		<#if object.trashcan == "true">
		final HTML undo = new HTML("<a href=javascript:void(0)>Undo</a>");
		undo.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				String ids = "";
				for (Long id : idList) {
					if (ids.isEmpty())
                        ids = String.valueOf(id);
                    else
                        ids = ids + "," + String.valueOf(id) ;
                }
				String _url = URL.encode(baseUrl + "_operationType=undo&id=" + ids);
				RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("Undo failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						JSONObject responseJSON = JSONParser.parse(response.getText())
							.isObject().get("response").isObject();
						if (!hasErrors(responseJSON)) {
							scrollTable.getDataTable().clearAll();
							createDataList(true);
							undo.setVisible(false);
						}
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}

		});
		
		HTML trash = new HTML("<a href=javascript:void(0)>Trash</a>");
		trash.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (scrollTable.getDataTable().getSelectedRows().size() < 1) {
					Window.alert("You must select a record first!");
					return;
				}
				Set<Integer> set = scrollTable.getDataTable().getSelectedRows();
				Iterator<Integer> it = set.iterator();
				idList.clear();
				String ids = "";
				while (it.hasNext()) {
					final int row = it.next();
					idList.add(Long.valueOf(scrollTable.getDataTable().getText(
							row, 0)));
					String id = scrollTable.getDataTable().getText(row, 0);
					if (ids.isEmpty())
                        ids = id;
                    else
                        ids = ids + "," + id ;
				}
				String _url = URL.encode(baseUrl + "_operationType=trash&id=" + ids);
				RequestBuilder builder = new RequestBuilder(
						RequestBuilder.GET, _url);
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("Trash failed!");
					}

					public void onResponseReceived(Request request,
							Response response) {
						JSONObject responseJSON = JSONParser.parse(response.getText())
							.isObject().get("response").isObject();
						if (!hasErrors(responseJSON)) {
							undo.setVisible(true);
							scrollTable.getDataTable().clearAll();
							createDataList(true);
						}
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}

		});
		</#if>
		
		HTML refresh = new HTML("<a href=javascript:void(0)>Refresh</a>");
		refresh.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				scrollTable.getDataTable().clearAll();
				createDataList(true);
				scrollTable.getDataTable().deselectAllRows();
				<#if object.trashcan == "true">
				undo.setVisible(false);
				</#if>
			}

		});
		
		HTML drop = new HTML("<a href=javascript:void(0)>Drop ${object.name} Table</a>");
		drop.addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent arg0) {
				if (!Window.confirm("Are you sure?"))
					return;
				String _url = URL.encode(baseUrl + "_operationType=dropTable");
				RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
				builder.setCallback(new RequestCallback() {
					public void onError(Request request, Throwable exception) {
						Window.alert("Drop ${object.name} Table failed!");
					}

					public void onResponseReceived(Request request,Response response) {
						JSONObject responseJSON = JSONParser.parse(response.getText())
								.isObject().get("response").isObject();
						if (!hasErrors(responseJSON)) {
							scrollTable.getDataTable().clearAll();
							scrollTable.getDataTable().resizeRows(0);
						}
					}
				});
				try {
					builder.send();
				} catch (RequestException e) {
					e.printStackTrace();
				}
			}
		});
		
		
		table.setWidget(0, 0, add);
		<#if object.trashcan == "true">
		table.setWidget(0, 1, trash);
		table.setWidget(0, 3, undo);
		undo.setVisible(false);
		<#else>
		table.setWidget(0, 1, delete);
		</#if>
		table.setWidget(0, 2, refresh);
		<#if object.trashcan == "true">
		//table.setWidget(0, 4, drop);
		<#else>
		//table.setWidget(0, 3, drop);
		</#if>
		return table;
	}
	
	/**
	 * Copy values from json to table.
	 * 
	 * @return the new dialog box
	 */
	public void copyValue(final FixedWidthGrid dataTable, JSONArray array, boolean showSetField) {
		dataTable.resizeRows(array.size());
		for (int i = 0; i < array.size(); i++) {
			JSONObject value = array.get(i).isObject();
            ${object.name?uncap_first}Map.put(Long.valueOf(value.get("id").toString()), value);
            final int row = i;
			if (value.get("id") != null
					&& !value.get("id").toString().equalsIgnoreCase("null")) {
				dataTable.setText(i, 0, value.get("id").toString());
			}
			<#assign position = 0 />
			<#list object.tableScope?children as att>
	  			<#if att?node_type == "element">
	  				<#if att?node_name == "xml">
	  				<#elseif att?node_name == "date" || att?node_name == "datetime">
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null") && value.get("${att.@name}").isString().stringValue().length() > 0)
				dataTable.setText(row, ${position}, value.get("${att.@name}").isString()
						.stringValue());
					<#elseif att?node_name == "enum">	
					<#assign position = position + 1 />
			if (value.get("${att.@class?uncap_first}") != null
					&& !value.get("${att.@class?uncap_first}").toString().equalsIgnoreCase(
							"null") && value.get("${att.@class?uncap_first}").isString().stringValue().length() > 0)
				dataTable.setText(row, ${position}, value.get("${att.@class?uncap_first}").isString()
						.stringValue());
	  				<#elseif att?node_name == "html" || att?node_name == "string">
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null") && value.get("${att.@name}").isString().stringValue().length() > 0)
				dataTable.setText(row, ${position}, value.get("${att.@name}").isString()
						.stringValue());
	  				<#elseif att?node_name == "boolean">
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null")) {
				CheckBox box = new CheckBox();
				box.setValue(Boolean.valueOf(value.get("${att.@name}").toString()));
				box.setEnabled(false);
				dataTable.setWidget(row, ${position}, box);
			}
	  				<#elseif att?node_name == "integer">
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(row, ${position}, value.get("${att.@name}").toString());
	  				<#elseif att?node_name == "long">
	  					<#if att.@parentClass[0]??>
	  				<#assign position = position + 1 />
	  		if (value.get("${att.@fieldName}") != null
					&& !value.get("${att.@fieldName}").toString().equalsIgnoreCase(
							"null")) {
		        final String _url = URL.encode("../${att.@parentClass?uncap_first}Operations.do?" + "_operationType=findById&fetchScope=list&id=" + value.get("${att.@fieldName}").toString());
		        HTML link = new HTML("<a href=javascript:void(0)>See details</a>");
				link.addClickHandler(new ClickHandler() {

		            public void onClick(ClickEvent arg0) {
		            	RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
		            	final Element element = dataTable.getEventTargetCell((Event) arg0.getNativeEvent());
						builder.setCallback(new RequestCallback() {
							public void onError(Request request, Throwable exception) {
								Window.alert("get${att.@parentClass}ById failed!");
							}
						
							public void onResponseReceived(Request request, Response response) {
								JSONObject responseJSON = JSONParser.parse(response.getText()).isObject().get("response").isObject();
								if (!hasErrors(responseJSON)) {
									JSONObject json = responseJSON.get("data").isObject();
									Set<String> keys = json.keySet();
									Iterator<String> it = keys.iterator();
									StringBuffer s = new StringBuffer();
									while(it.hasNext()){
										String key = it.next();
										if (!key.equalsIgnoreCase("id")) {
						                	if (json.get(key).toString().contains("\""))
                                                s.append(json.get(key).isString().stringValue());
                                            else
                                                s.append(json.get(key).toString());
                                            s.append(" ");
						            	}
									}
									element.setInnerText(s.toString());
								}
							}
						});
						try {
							builder.send();
						} catch (RequestException e) {
							e.printStackTrace();
						}
		            }

        		});
				dataTable.setWidget(row, ${position}, link);
			}
						<#else>
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(row, ${position}, value.get("${att.@name}").toString());
						</#if>
					<#elseif att?node_name == "double">
	  				<#assign position = position + 1 />
			if (value.get("${att.@name}") != null
					&& !value.get("${att.@name}").toString().equalsIgnoreCase(
							"null"))
				dataTable.setText(row, ${position}, value.get("${att.@name}").toString());
					<#else>
			ERROR, undefined node ${att?node_name}
					</#if>
	  			</#if>
			</#list>
			<#if object.attributes.set[0]??>
			if (showSetField) {
				<#list object.attributes.set as att>
				<#assign position = position + 1 />
				HTML ${att.@plural}Link = new HTML("<a href=javascript:void(0)>?</a>");
				${att.@plural}Link.addClickHandler(new ClickHandler() {

		            public void onClick(ClickEvent arg0) {
		            	dataTable.selectRow(row, true);
		                PopupPanel list = create${att.@plural?cap_first}List(row);
						list.setGlassEnabled(true);
						list.setAnimationEnabled(true);
						list.center();
						list.show();
		            }

        		});
				dataTable.setWidget(row, ${position}, ${att.@plural}Link);	
				</#list>
			}
			</#if>	
		}
	}
	
	/**
	 * Create the dialog box for this add form.
	 * 
	 * @return the new dialog box
	 */
	private PopupPanel createPopupPanel(boolean isNew) {
		// Create a dialog box and set the caption text
		final PopupPanel popupPanel = new PopupPanel(true);
		popupPanel.setStyleName("redora-popups-Popup");
		HTML msg = new HTML("<center><b>Add Or Update ${object.name} Form</b></center>", false);
		popupPanel.setTitle("Add Or Update ${object.name} Form");

		
		form.setAction(baseUrl);
        form.setEncoding(FormPanel.ENCODING_URLENCODED);
        form.setMethod(FormPanel.METHOD_POST);
        VerticalPanel formPanel = new VerticalPanel();
        form.setWidget(formPanel);
        
        //clearFormStyle();
        ErrorHandler.resetFormStyle(formTable);
        
        //action type
        TextBox _operationType = new TextBox();
        _operationType.setName("_operationType");
        _operationType.setValue("persist");
        _operationType.setVisible(false);
        formPanel.add(_operationType);     
		
		//FlexTable formTable = new FlexTable();
		formTable.setCellSpacing(6);
		
		id.setReadOnly(true);
		formTable.setHTML(0, 0, "Id:");
		formTable.setWidget(0, 1, id);
		id.setName("id");
		id.getElement().setId("id");
		id.setValue(null);
		<#assign position = 0 />
		<#list object.formScope?children as att>
			<#if att?node_name != "object" && att?node_type == "element">
				<#if att?node_name == "xml">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");
			  	<#elseif att?node_name == "date" || att?node_name == "datetime">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		${att.@fieldName}.setTitle("${att.@fieldName}");
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setReadOnly(true);
		DatePicker ${att.@fieldName}DatePicker = new DatePicker();
		${att.@fieldName}DatePicker.addValueChangeHandler(new ValueChangeHandler<Date>() {

			public void onValueChange(ValueChangeEvent<Date> arg0) {
				Date date = arg0.getValue();
				<#if att?node_name == "date">
				String dateString = DateTimeFormat.getFormat(DATE)
						.format(date);
				<#elseif att?node_name == "datetime">
				String dateString = DateTimeFormat.getFormat(DATETIME)
						.format(date);
				<#else>
				</#if>
				${att.@fieldName}.setValue(dateString);
			}

		});
		formTable.setWidget(${position}, 2, ${att.@fieldName}DatePicker);
			  	<#elseif att?node_name == "enum">
			  	<#assign position = position + 1 />
		${att.@fieldName}.clear();
		<#if !att.@notnull[0]?? || att.@notnull[0] == "false">
		${att.@fieldName}.addItem("","");
		</#if>
					<#list att.element as value>
		${att.@fieldName}.addItem(constants.${object.name?uncap_first}_${att.@fieldName}_${value.@name}_form(),"${value.@name}");
					</#list>
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
			  	<#elseif att?node_name == "html">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		${att.@fieldName}RichText.setHTML(null);
		${att.@fieldName}RichText.setSize("100%", "10em");
		RichTextToolbar ${att.@fieldName}Toolbar = new RichTextToolbar(${att.@fieldName}RichText);
		${att.@fieldName}Toolbar.setWidth("100%");
		Grid ${att.@fieldName}Grid = new Grid(2, 1);
	    ${att.@fieldName}Grid.setWidget(0, 0, ${att.@fieldName}Toolbar);
	    ${att.@fieldName}Grid.setWidget(1, 0, ${att.@fieldName}RichText);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName}Grid);
		formPanel.add(${att.@fieldName});
		${att.@fieldName}.setVisible(false);
		//formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		//formTable.setWidget(${position}, 1, ${att.@fieldName});
		//${att.@fieldName}.setTitle("${att.@fieldName}");
				<#elseif att?node_name == "string">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");
				<#elseif att?node_name == "boolean">
				<#assign position = position + 1 />
		${att.@fieldName}CheckBox.setValue(false);
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName}CheckBox);
		${att.@fieldName}CheckBox.setTitle("${att.@fieldName}");
		${att.@fieldName}CheckBox.setFormValue("true");
		formPanel.add(${att.@fieldName});
		${att.@fieldName}.setVisible(false);
				<#elseif att?node_name == "integer">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");
		NumCheckValidator ${att.@fieldName}NumCheckValidator = new NumCheckValidator();
		ValidatorController.addAsFocusListener(${att.@fieldName}, ${att.@fieldName}NumCheckValidator);
				<#elseif att?node_name == "long">
				<#assign position = position + 1 />
					<#if att.@parentClass[0]??>
		${att.@fieldName}.clear();
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");
						<#if !att.@notnull[0]?? || att.@notnull[0] == "false">
		${att.@fieldName}.addItem("","");
						</#if>
		get${att.@fieldName?cap_first}List(${att.@fieldName},isNew);
					<#else>
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");
		NumCheckValidator ${att.@fieldName}NumCheckValidator = new NumCheckValidator();
		ValidatorController.addAsFocusListener(${att.@fieldName}, ${att.@fieldName}NumCheckValidator);
					</#if> 
				<#elseif att?node_name == "double">
				<#assign position = position + 1 />
		${att.@fieldName}.setValue(null);
		formTable.setHTML(${position}, 0, constants.${object.name?uncap_first}_${att.@fieldName}_form() + ":");
		formTable.setWidget(${position}, 1, ${att.@fieldName});
		${att.@fieldName}.setTitle("${att.@fieldName}");   
				<#else>
		ERROR, undefined node ${att?node_name}
				</#if>
				<#if att?node_name == "long" && att.@parentClass[0]??>
		${att.@fieldName}.setName("${att.@fieldName}");
        ${att.@fieldName}.getElement().setId("${att.@fieldName}");
        		<#else>
        ${att.@fieldName}.setName("${att.@fieldName}");
        ${att.@fieldName}.getElement().setId("${att.@fieldName}");
        			<#if att.@notnull[0] == "true">
        				<#if att?node_name == "boolean" || att?node_name == "enum">
        				<#else>
        NotNullValidator ${att.@fieldName}Validation = new NotNullValidator();
		ValidatorController.addAsFocusListener(${att.@fieldName}, ${att.@fieldName}Validation);
						</#if>
					</#if>
					<#if att.@regexp[0]??>
		RegExpValidator ${att.@fieldName}CheckRegexpValidation = new RegExpValidator("${att.@regexp}");
		ValidatorController.addAsFocusListener(${att.@fieldName}, ${att.@fieldName}CheckRegexpValidation);
					</#if>
        		</#if>
			</#if>
		</#list>
		formTable.setHTML(${position+1}, 0, "creationDate:");
		formTable.setWidget(${position+1}, 1, creationDate);
		creationDate.setReadOnly(true);
		creationDate.setValue(null);
		formTable.setHTML(${position+2}, 0, "updateDate:");
		formTable.setWidget(${position+2}, 1, updateDate);
		updateDate.setReadOnly(true);
		updateDate.setValue(null);
		
		if (!isNew) { 
			Set<Integer> set = scrollTable.getDataTable().getSelectedRows();
			Iterator<Integer> it = set.iterator();
			int row = it.next();
			copyToForm(row);
		}
		
		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		popupPanel.setWidget(dialogContents);

		dialogContents.add(msg);
		dialogContents.add(form);
		       
        formPanel.add(formTable);
        
        // Add a 'submit' button.
        Button submit = new Button("Submit", new ClickHandler() {
          public void onClick(ClickEvent event) {
              form.submit();
          }
        });
        // Add a close button at the bottom of the dialog
		Button close = new Button("close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				popupPanel.hide();
			}
		});
        
        // Add an event handler to the form.
        form.addSubmitHandler(new FormPanel.SubmitHandler() {
         	public void onSubmit(SubmitEvent event) {
        		<#list object.formScope?children as att>
        			<#if att?node_name == "html">
        		${att.@fieldName}.setValue(${att.@fieldName}RichText.getHTML());
        			<#elseif att?node_name == "boolean">
        		if (${att.@fieldName}CheckBox.getValue())
        			${att.@fieldName}.setValue("true");
        		else
        			${att.@fieldName}.setValue("false");
        			</#if>
        		</#list>
          }
        });
        form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
          	public void onSubmitComplete(SubmitCompleteEvent event) {
          		ErrorHandler.resetFormStyle(formTable);
           		String result = event.getResults();
                JSONObject responseJSON = JSONParser.parse(result).isObject().get("response").isObject();
				if (!hasErrors(responseJSON)) {
					scrollTable.getDataTable().clearAll();
					createDataList(true);
					popupPanel.hide();
				}
          	}
        });

		HorizontalPanel panel = new HorizontalPanel();
		panel.add(submit);
		panel.add(close);
		dialogContents.add(panel);

		// Return the dialog box
		return popupPanel;
	}
	
	/**
	 * Copy values from json to form.
	 * 
	 * @return the new dialog box
	 */
	public void copyToForm(int row) {
		Long idVal = Long.valueOf(scrollTable.getDataTable().getText(row, 0));
		JSONObject jsonValue = ${object.name?uncap_first}Map.get(idVal);
		id.setValue(scrollTable.getDataTable().getText(row,0));
		<#assign position = 0 />
		<#list object.tableScope?children as att>
			<#if att?node_type == "element" && att?node_name != "object">
				<#if att?node_name == "xml">
				<#elseif att?node_name == "date" || att?node_name == "datetime">
		if (!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString()))
			${att.@name}.setValue(jsonValue.get("${att.@name}").toString());
				<#elseif att?node_name == "enum">
		if (!jsonValue.get("${att.@class?uncap_first}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString()))
			for (int i = 0; i < ${att.@class?uncap_first}.getItemCount(); i++) {
				if (${att.@class?uncap_first}.getValue(i).equalsIgnoreCase(jsonValue.get("${att.@class?uncap_first}").isString().stringValue()))
					${att.@class?uncap_first}.setSelectedIndex(i);
			}
			  	<#elseif att?node_name == "html">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString())) {
			${att.@name}.setValue(jsonValue.get("${att.@name}").isString().stringValue());
			${att.@name}RichText.setHTML(jsonValue.get("${att.@name}").isString().stringValue());
		}
				<#elseif att?node_name == "string">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString())) 
			${att.@name}.setValue(jsonValue.get("${att.@name}").isString().stringValue());
				
			  	<#elseif att?node_name == "boolean">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString())) {
			${att.@name}CheckBox.setValue(Boolean.valueOf(jsonValue.get("${att.@name}").toString()));
			${att.@name}.setValue(jsonValue.get("${att.@name}").toString());
		}
				<#elseif att?node_name == "integer">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString()))
			${att.@name}.setValue(jsonValue.get("${att.@name}").toString());
				<#elseif att?node_name == "long">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString())) {
					<#if att.@parentClass[0]??>
			for (int i = 0; i < ${att.@fieldName}.getItemCount(); i++) {
				if (${att.@fieldName}.getValue(i).equalsIgnoreCase(jsonValue.get("${att.@name}").toString()))
					${att.@fieldName}.setSelectedIndex(i);
			}
					<#else>
			${att.@name}.setValue(jsonValue.get("${att.@name}").toString());
					</#if>
		}
				<#elseif att?node_name == "double">
		if(!jsonValue.get("${att.@name}").toString().equalsIgnoreCase(JSONNull.getInstance().isNull().toString()))
			${att.@name}.setValue(jsonValue.get("${att.@name}").toString());
				<#elseif att?node_name == "set">
				<#else>
		ERROR, undefined node ${att?node_name}
				</#if>
			</#if>
		</#list>
		creationDate.setValue(jsonValue.get("creationDate").isString().stringValue());
        if (!jsonValue.get("updateDate").toString().equalsIgnoreCase(
        	JSONNull.getInstance().isNull().toString()))
        	updateDate.setValue(jsonValue.get("updateDate").isString().stringValue());
		<#if object.lazyScope[0]??>
		String _url = URL.encode(baseUrl + "_operationType=fetchLazy&id=" + scrollTable.getDataTable().getText(row,0));
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("fetch lazy field failed!");
			}
	
			public void onResponseReceived(Request request, Response response) {
				JSONObject responseJSON = JSONParser.parse(response.getText()).isObject().get("response").isObject();
				if (!hasErrors(responseJSON)) {
					JSONObject json = responseJSON.get("data").isObject();
					id.setValue(json.get("id").toString());
				<#list object.lazyScope?children as att>
					<#if att?node_name != "object" && att?node_type == "element">
					if (json.get("${att.@fieldName}") != null && !"null".equalsIgnoreCase(json.get("${att.@fieldName}").toString())) {
						<#if att?node_name == "xml">
						${att.@fieldName}.setText(json.get("${att.@fieldName}").isString().stringValue());;
					  	<#elseif att?node_name == "html">
						${att.@fieldName}.setText(json.get("${att.@fieldName}").isString().stringValue());
						${att.@fieldName}RichText.setHTML(json.get("${att.@fieldName}").isString().stringValue());
						<#elseif att?node_name == "string">
						${att.@fieldName}.setText(json.get("${att.@fieldName}").isString().stringValue());
						<#else>
						ERROR, undefined node ${att?node_name}
						</#if>
					}
					</#if>
				</#list>
				}
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
		</#if>
	}
			
	<#list doc["/object/attributes/long"] as att>
		<#if att.@parentClass[0]??>
	private void get${att.@fieldName?cap_first}List(final ListBox ${att.@fieldName}, final boolean isNew){
		String _url = URL.encode("../${att.@parentClass?uncap_first}Operations.do?" + "_operationType=fetch&fetchScope=list");
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("get${att.@fieldName?cap_first}List failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONObject responseJSON = JSONParser.parse(response.getText()).isObject().get("response").isObject();
				if (!hasErrors(responseJSON)) {
					JSONArray jsons = responseJSON.get("data").isArray();
					for(int i = 0; i< jsons.size();i++){
						Set<String> keys = jsons.get(i).isObject().keySet();
						Iterator<String> it = keys.iterator();
						StringBuffer s = new StringBuffer();
						while(it.hasNext()){
							String key = it.next();
							if (!key.equalsIgnoreCase("id")) {
						    	if (jsons.get(i).isObject().get(key).toString().contains("\""))
                            		s.append(jsons.get(i).isObject().get(key).isString().stringValue());
                            	else
                                    s.append(jsons.get(i).isObject().get(key).toString());
                                s.append(" ");
						    }
						}
						${att.@fieldName}.addItem(s.toString(),jsons.get(i).isObject().get("id").toString());
					}
					if (!isNew) {
						Set<Integer> set = scrollTable.getDataTable().getSelectedRows();
						Iterator<Integer> it = set.iterator();
						int row = it.next();
						Long id = Long.valueOf(scrollTable.getDataTable().getHTML(row, 0));
						JSONObject json = ${object.name?uncap_first}Map.get(id);
						if (!json.get("${att.@fieldName}").toString()
	                            .equalsIgnoreCase(JSONNull.getInstance().toString())) {
							for (int i = 0; i < ${att.@fieldName}.getItemCount(); i++) {
								if (${att.@fieldName}.getValue(i).equalsIgnoreCase(
										json.get("${att.@fieldName}").toString()))
									${att.@fieldName}.setSelectedIndex(i);
							}
						}
					}
				}
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}
		</#if>
	</#list>
	
	<#assign position = 0>
	<#list object.tableScope?children as att>
	  	<#if att?node_type == "element">
	  		<#assign position = position + 1>
	  	</#if>
	</#list>
	<#list object.attributes.set as att>
	<#assign position = position + 1>
	private PopupPanel create${att.@plural?cap_first}List(final int row) {
		Long id = Long.valueOf(scrollTable.getDataTable().getText(row, 0));
		final PopupPanel popupPanel = new PopupPanel(true);
		popupPanel.setStyleName("redora-popups-Popup");
		popupPanel.setWidth("800");
		popupPanel.setHeight("250");
		HTML msg = new HTML("<center><b>${att.@class} List</b></center>", false);
		popupPanel.setTitle("${att.@class} list");
		VerticalPanel dialogContents = new VerticalPanel();
		dialogContents.setSpacing(4);
		popupPanel.setWidget(dialogContents);

		final ${att.@class}ViewPanel panel = new ${att.@class}ViewPanel();

		FixedWidthFlexTable headerTable = panel.createHeaderTable(false);
		FixedWidthFlexTable footerTable = panel.createFooterTable();
		final FixedWidthGrid dataTable = panel.createDataTable(false);
		dataTable.unsinkEvents(Event.ONBLUR | Event.ONCLICK | Event.ONDBLCLICK);

		// Combine the components into a ScrollTable
		ScrollTable ${att.@class?uncap_first}scrollTable = new ScrollTable(dataTable, headerTable);
		${att.@class?uncap_first}scrollTable.setFooterTable(footerTable);

		// Set some options in the scroll table
		// scrollTable.setSortingEnabled(true);
		${att.@class?uncap_first}scrollTable.setResizePolicy(ScrollTable.ResizePolicy.FILL_WIDTH);
		${att.@class?uncap_first}scrollTable.setSize("800", "200");

		// Setup some default widths
		${att.@class?uncap_first}scrollTable.setColumnWidth(2, 50);
		${att.@class?uncap_first}scrollTable.setColumnWidth(5, 50);

		String _url = URL.encode("../${att.@class?uncap_first}Operations.do?"
				+ "_operationType=findBy${att.@myKey?cap_first}&fetchScope=table&${att.@myKey}=" + id);
		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, _url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				Window.alert("create${att.@class}List failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				if (response.getText() != null && response.getText().trim().length() > 0) {
					JSONObject responseJSON = JSONParser.parse(response.getText()).isObject().get("response").isObject();
					if (!hasErrors(responseJSON)) {
						JSONArray jsons = responseJSON.get("data").isArray();
						panel.copyValue(dataTable, jsons, false);
						HTML link = (HTML) scrollTable.getDataTable().getWidget(row, ${position});
                        link.setHTML("<a href=javascript:void(0)>"
                                + String.valueOf(jsons.size()) + "</a>");
						scrollTable.getDataTable().setWidget(row, ${position}, link);
					}
				} else 
					scrollTable.getDataTable().setText(row, ${position}, "0");
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
		dialogContents.add(msg);
		dialogContents.add(${att.@class?uncap_first}scrollTable);
		Button closeButton = new Button("close", new ClickHandler() {
			public void onClick(ClickEvent event) {
				popupPanel.hide();
			}
		});
		dialogContents.add(closeButton);
		return popupPanel;
	}
	</#list>
	
	public boolean hasErrors(JSONObject response) {
        if (response.get("status").toString().equalsIgnoreCase(
                redora.client.util.Constants.ERROR_CODE_BUSINESSRULE_CHECK)) {
            JSONArray array = response.get("error").isArray();
            for (int i = 0; i < array.size(); i++) {
                JSONObject br = array.get(i).isObject();
                String errorMessage = null;
                <#if object.businessRules[0]??>
                	<#list object.businessRules.businessRule as br>
                if ("${br.@number}".equalsIgnoreCase(br.get("businessRuleId").toString())) {
                		<#if br.params[0]??> 
                 	if (br.get("messages") != null) {
                        JSONArray arguments = br.get("messages").isArray();
<#macro copy_arg br>
<#assign maxNumber = 0>
<#assign num = 0>
<#list br.params.param as param>
	<#assign num = num + 1>
	<#if param?contains(',')>
		<#assign index = param?index_of(',')>
		<#assign param = param?substring(0,index)>
	</#if>
	<#if param?number gte maxNumber>
	<#assign maxNumber = param?number>
	<#if num gt 1>,</#if>arguments.get(${param?number}).isObject().get("arguments").toString()
	</#if>
</#list>
</#macro>
                        errorMessage = messages.${object.name?uncap_first}_businessRule_${br.@number}(<@copy_arg br=br/>);
                    }
                		<#else>
                	errorMessage = messages.${object.name?uncap_first}_businessRule_${br.@number}();
                		</#if> 
                }
                	</#list>
                </#if>
                if (br.get("field") != null) {
                	if (errorMessage == null)
                		errorMessage = br.get("field").isString().stringValue() + " is wrong!";
                	ErrorHandler.errorHandler(formTable, br.get("field").isString().stringValue(),errorMessage);
                }
                else
                	ErrorHandler.errorHandler(formTable, null,errorMessage);
            }
            return true;
        } else if (response.get("status").toString().equalsIgnoreCase(
                redora.client.util.Constants.ERROR_CODE_EXCEPTION)) {
            Window.alert(response.get("error").toString());
            return true;
        } else if (response.get("status").toString().equalsIgnoreCase(
                redora.client.util.Constants.ERROR_CODE_UNSAVED)) {
            Window.alert("Nothing has been changed ,Do not save!");
            return true;
        }
        return false;
    }
}
